package db;

import beans.MessageBean;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;

/**
 * Message in one forum, is possible to add, edit or delete message.
 * @author Tomas CASTA
 */
public class Message {
    /** one message in forum */
    private MessageBean message;
    /** connection to db */
    private Connection connection;
     /** message for errors */
    private String msg;
   /** servlet context */
    private ServletContext context;
    /** statement for queries */
    private PreparedStatement stmt;
    /** set for results */
    private ResultSet resultSet;

    /**
     * Constructor.
     */
    public Message() {
    }

    public MessageBean getMessage() {
        return message;
    }

    public void setMessage(MessageBean message) {
        this.message = message;
    }

     /**
     * Set connection to db.
     * @param context ServletContext context of actual servler
     * @return boolean true ok, false error
     */
    public boolean setDb(ServletContext context) {
        this.context = context;
        Db db = new Db();

        /* Get params from web.xml */
        db.setDb(context.getInitParameter("db-machine"), context.getInitParameter("db-db"), context.getInitParameter("db-user"), context.getInitParameter("db-pass"));
        this.connection = db.connectToDB();
        msg = db.getMsg();
        if (this.connection == null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Delete message by given id.
     * @param id int id message to delete
     * @return int 0 error, 1 ok, 2 last message in forum
     */
    public int deleteMessage(int id) {
        try {

            /* Get message to delete */
            stmt = this.connection.prepareStatement("SELECT * FROM casta_message WHERE id = ?");
            stmt.setInt(1, id);
            resultSet = stmt.executeQuery();

            int idForum = -1;
            int count = -1;

            /* Get forum id od message */
            while (resultSet.next()) {
                idForum  = resultSet.getInt("id_forum");
            }

            /* Select all messages in this forum */
            stmt = this.connection.prepareStatement("SELECT * FROM casta_message WHERE id_forum = ?");
            stmt.setInt(1, idForum);
            resultSet = stmt.executeQuery();
            resultSet.last();
            count = resultSet.getRow();

            /* Last message in forum, delete forum */
            if (count == 1) {
                Forum forum = new Forum();
                forum.setDb(context);
                forum.deleteForum(idForum);
                stmt.close();
                connection.close();
                return 2;

            }

            /* Delete message */
            stmt = this.connection.prepareStatement("DELETE FROM casta_message WHERE id = ?");
            stmt.setInt(1, id);

            /* Error in query */
            if (stmt.executeUpdate() != 1) {
                stmt.close();
                connection.close();
                return 0;
            }

            stmt.close();
            connection.close();
            return 1;

        } catch (SQLException ex) {
            Logger.getLogger(Forum.class.getName()).log(Level.SEVERE, null, ex);
            return 0;
        }

        catch (NullPointerException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
            msg = "Databáze není přístupná.";
            return 0;
        }


    }

    /**
     * Edit message by given id.
     * @param id int message id in forum
     * @param text String message text for update
     * @return boolean true ok, false error
     */
    public boolean editMessage(int id, String text) {
        try {

            /* Update message in forum */
            stmt = this.connection.prepareStatement("UPDATE casta_message SET text = ? WHERE id = ?");

            /* Add <pre> tag for linefeed */
            stmt.setString(1, text);
            stmt.setInt(2, id);

            /* Error in query */
            if (stmt.executeUpdate() != 1) {
                stmt.close();
                connection.close();
                return false;
            }

            stmt.close();
            connection.close();
            return true;

        } catch (SQLException ex) {
            Logger.getLogger(Forum.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }

        catch (NullPointerException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
            msg = "Databáze není přístupná.";
            return false;
        }

    }


    /**
     * Show one message by given id.
     * @param id int message id
     * @return boolean true ok, false error
     */
    public boolean showMessage(int id) {
        try {

            /* Get info about mesage */
            stmt = this.connection.prepareStatement("SELECT * FROM casta_message WHERE id = ?");
            stmt.setInt(1, id);
            resultSet = stmt.executeQuery();

            /* Get info about author */
            if (resultSet.next()) {
                User user = new User();
                user.setDb(context);
                user.findById(resultSet.getInt("id_user"));
                message = new MessageBean(resultSet.getInt("id"), resultSet.getInt("id_forum"), resultSet.getInt("id_user"), resultSet.getString("posted_at"), resultSet.getString("text"), user.getUserBean());
            }
            stmt.close();
            connection.close();
            return true;

        } catch (SQLException ex) {
            Logger.getLogger(Forum.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }

        catch (NullPointerException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
            msg = "Databáze není přístupná.";
            return false;
        }
    }
}
